/*
 * @Author: Jiraiya
 * @Date: 2020-05-06 16:07:43
 * @LastEditors: Jiraiya
 * @LastEditTime: 2020-05-08 10:56:48
 * @Description: 
 */
const debug = require('debug')('koa-next');
const bee = global.bee;

module.exports = function (opts){
    opts = Object.assign(Object.create(null), opts);
    const {nextApp, nextHandle} = opts;
    const { utils } = bee;
    const rewriteRule = bee.getSystemConfig('rewrite') || [];
    return async function server(ctx, next){
        const {req, res, path, query} = ctx;
        res.statusCode = 200;
        await next();

        // 判断是api还是其他
        if(utils.isApi(path, bee.apiRoot)){    
            await nextHandle(req, res);
        }else{
            const {params, real} = utils.matchRouter(path, rewriteRule);
            await nextApp.render(req, res, real, Object.assign(Object.create(null), params, query));
        }
        
        ctx.respond = false;
    }
}